import proj4 from 'proj4';
import {register} from 'ol/proj/proj4'
import { Projection,addProjection} from 'ol/proj';
//天地图底图WMTS加载
import {getWidth,getTopLeft} from 'ol/extent';
import TileLayer from 'ol/layer/Tile';
import TileGrid from 'ol/tilegrid/TileGrid';
import TileImage from 'ol/source/TileImage';


//将4490注册到projection中
proj4.defs("EPSG:4490","GEOGCS[\"China Geodetic Coordinate System 2000\",DATUM[\"China_2000\",SPHEROID[\"CGCS2000\",6378137,298.257222101,AUTHORITY[\"EPSG\",\"1024\"]],AUTHORITY[\"EPSG\",\"1043\"]],PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",\"8901\"]],UNIT[\"degree\",0.0174532925199433,AUTHORITY[\"EPSG\",\"9122\"]],AUTHORITY[\"EPSG\",\"4490\"]]");
register(proj4);

//重写projection4490
var projection = new Projection({
code: 'EPSG:4490',
units: 'degrees',
axisOrientation: 'neu'
});
projection.setExtent([-180, -90, 180, 90]);
projection.setWorldExtent([-180, -90, 180, 90]);
//覆盖添加到projection中
addProjection(projection);

export function getProjection() {
    return projection
}
//地图服务网址
export function iServerHttp(){
    // return "http://10.13.155.192:8090"
    return "http://10.7.208.233:8080"
}
let projectionExtent = projection.getExtent();
let size = getWidth(projectionExtent) / 256; //size就是一个像素代表的经纬度
//自定义比例尺（天地图fxpc）
let scaleDenominators = [279541132.0143589,139770566.0071794,69885283.00358972,34942641.50179486,18471320.75089743,8735660.375448715,4367830.1877243575,2183915.0938621787,1091957.5469310891,545978.7734655447,272989.38673277234,136494.6933663862,68247.34668319309,34123.67334159654,17061.83667079827,8530.918335399136,4265.459167699568,2132.729583849784];
//从0开始的第4项比例尺有问题（17471320.75089743），地图显示有偏移，修改为18471320.75089743

//自定义比例尺（天地图fxpc）
export function getResolutions() {
    let resolutions = [];
    for (var z = 0; z < 18; ++z) {
        //resolutions[z] = size / Math.pow(2, z);
        //比例尺、分辨率计算公式：scale = 1 : (resolution * dpi/0.0254)
        //let scale = 1 / scaleDenominators[z];
        //let degree = meter / (2 * Math.PI * 6371004) * 360;//度、米转换公式
        let dpi = 90.7142857142857;
        resolutions[z] = scaleDenominators[z] * 0.0254 / dpi / (2 * Math.PI * 6378137) * 360;
    }

    return resolutions;
}

function getMatrixIds() {
    let matrixIds = [];
    for (let z = 0; z < 18; ++z) {
        matrixIds[z] = z;
    }
    return matrixIds;
}

//获取tileGrid（自定义比例尺）
export function getTileGrid(origin,extent) {
    return new TileGrid({
        //origin: getTopLeft(projectionExtent),
        //origin: [-180.0, 90.0],
        //extent: [-180.0, -90.0, 180.0, 90.0],
        //origin: [73.1793, 53.7509],
        //extent: [73.1793, 15.5126, 135.3954, 53.7509],
        origin: origin,
        extent: extent,
        resolutions: getResolutions(),
        matrixIds: getMatrixIds(),
        tilesSize: [256, 256]
    });
}

//获取超图发布的WMTS图层（自定义比例尺）
export function getWMTSLayer(wmtsUrl,layerName,origin,extent) {
    //获取tileGrid（自定义比例尺）
    let tileGrid = getTileGrid(origin,extent);

    return new TileLayer({
        source: new TileImage({
            projection: projection,
            tileGrid: tileGrid,
            tileUrlFunction: function (tileCoord, pixelRatio, proj) {
                if (!tileCoord) {
                    return "";
                }
                let z = tileCoord[0];
                let x = tileCoord[1];
                let y = tileCoord[2];
                //return 'http://10.13.155.192:8090/iserver/services/map-fxfzypg/wmts-fxpc/district_boundary_province@fxfzypg/default/Custom_district_boundary_province@fxfzypg/'+z+'/'+y+'/'+x+'.png';
                return wmtsUrl+'/'+layerName+'/default/Custom_'+layerName+'/'+z+'/'+y+'/'+x+'.png';
            }
        })
    });
}

//获取超图发布的REST图层（自定义比例尺）
export function getRESTLayer(layerUrl,layerID,origin,extent) {
    console.log("origin");
    console.log(origin);
    console.log("extent");
    console.log(extent);
    //获取tileGrid（自定义比例尺）
    let tileGrid = getTileGrid(origin,extent);
    let version = Math.random();
    if(layerID==null){//临时图层ID
        layerID = "";
    }

    return new TileLayer({
        source: new TileImage({
            projection: projection,
            tileGrid: tileGrid,
            tileUrlFunction: function (tileCoord, pixelRatio, proj) {
                console.log(tileCoord);
                if (!tileCoord) {
                    return "";
                }
                let z = tileCoord[0];
                let x = tileCoord[1];
                let y = tileCoord[2];
                /*if (z==4) {//地图有偏移，可能是比例尺问题，暂不显示第4级
                    return "";
                }*/
                let scale = 1 / scaleDenominators[z];
                let resultUrl = layerUrl+'/tileImage.png?scale='+scale+'&x='+x+'&y='+y+'&width=256&height=256&layersID='+layerID+'&transparent=true&tileversion='+version;
                //console.log(resultUrl);
                return resultUrl;
            }
        })
    });
}
//获取超图发布的REST矢量切片图层（自定义比例尺）
export function getVectorTileLayer(map,layerUrl,origin,extent,view,serviceResult,sqlText,minZoom) {
    //处理sql对象
    let sqlObjArray = [];
    if(sqlText!=null && sqlText!==""){
        let sqlArray = sqlText.split("and");
        for(let i=0;i<sqlArray.length;i++){
            let sqlStrArr = sqlArray[i].trim().split(" like ");
            let fieldProp = sqlStrArr[0];
            let fieldValue = sqlStrArr[1];
            let sqlObj = {
                fieldProp:fieldProp,
                fieldValue:fieldValue
            }
            sqlObjArray.push(sqlObj);
        }
    }
    /*//test
    sqlObjArray = [{
        fieldProp:"name",
        fieldValue:"'%北京%'"
    }];*/
    console.log("sqlObjArray");
    console.log(sqlObjArray);
    //矢量瓦片风格参数对象
    let stylesOptions = {
        url: layerUrl,
        view: view
    };
    //创建瓦片风格对象
    let vectorTileStyles = new VectorTileStyles(stylesOptions);
    console.log("vectorTileStyles");
    console.log(vectorTileStyles);
    //通过地图信息获取瓦片参数对象
    // let vectorTileOptions = VectorTileSuperMapRest.optionsFromMapJSON(layerUrl, serviceResult);
    //自定义瓦片参数对象
    let vectorTileOptions = {};
    vectorTileOptions.url = layerUrl;
    vectorTileOptions.crossOrigin = 'anonymous';
    //获取tileGrid（自定义比例尺）
    let tileGrid = getTileGrid(origin,extent);
    vectorTileOptions.tileGrid = tileGrid;
    vectorTileOptions.sqlObjArray = sqlObjArray;//设置sql查询对象数组
    vectorTileOptions.projection = projection;//设置projection4490
    // vectorTileOptions.view = view;
    // vectorTileOptions.minZoom = 10;//最小显示的地图级别
    console.log("vectorTileOptions");
    console.log(vectorTileOptions);
    let source = new VectorTileSuperMapRest(vectorTileOptions);//重写tileUrlFunction、tileLoadFunction（自定义比例尺）
    console.log("source");
    console.log(source);

    //返回超图发布的REST矢量切片图层（自定义比例尺）
    let layer = new VectorTileLayer({
        minZoom:minZoom,
        source: source,
        style: vectorTileStyles.featureStyleFuntion
    });

    return [layer,vectorTileStyles];
}